package com.pdsu.alumni.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pdsu.alumni.common.annotation.CurrentUser;
import com.pdsu.alumni.common.result.Result;
import com.pdsu.alumni.pojo.*;
import com.pdsu.alumni.service.*;
import com.pdsu.alumni.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Acerola
 * @since 2021-11-05
 */
@Api(tags = "新闻控制层")
@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private IMessageService messageService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private UserService userService;
    @Autowired
    private IMessageTypeService messageTypeService;
    @Autowired
    private IFilesService filesService;
    @Autowired
    private ICoverService coverService;

    @ApiOperation(value = "获取所有新闻")
    @GetMapping("/getList")
    @RequiresAuthentication
    @ResponseBody
    @CrossOrigin
    public Result<?> getAllMessage() {
        QueryWrapper<Message> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 1);
        List<Message> list = messageService.list(wrapper);
        //按发布日期倒序
        list.sort(Comparator.comparing(Message::getSendTime));
        Collections.reverse(list);
        return new Result<>().success().put(list);
    }

    @ApiOperation(value = "添加新闻")
    @PostMapping("/add")
    @RequiresAuthentication
    @RequiresPermissions("message:add")
    @ResponseBody
    @CrossOrigin
    public Result<?> messageAdd(@CurrentUser User user, @RequestBody Map map0) {
        Map map = (Map) map0.get("map");
        Object message1 = map.get("message");
        Message message = JSON.parseObject(JSON.toJSONString(message1), Message.class);
        List<Role> roles = userRoleService.queryRolesByUserId(user.getUserId());
        Role role = roles.get(0);
        //暂时就不做标题重复了
//        QueryWrapper<Message> wapper = new QueryWrapper<>();
//        wapper.eq("title", message.getTitle());
//        int count = messageService.count(wapper);
//        if (count > 0) {
//            return new Result<>().error(500, "标题重复");
//        }
        /**
         * 1 已发布
         * 2 待审核
         * 3 审核失败
         */
        message.setUserName(user.getUserName());
        message.setExaminer(user.getUserName());
        message.setState("2");
        message.setSendTime(DateUtil.formatMinute(new Date()));
        message.setDeleted(1);
        message.setPublisherFaculty(user.getUserFaculty());
        message.setPublisherRank(role.getRoleName());
        message.setPublisherLevel(role.getRoleLevel());
        messageService.save(message);
        //封面保存,如果封面为null,则从imgSrc拿封面
        Map mc = (Map) map.get("cover");
        System.out.println("**************");
        System.out.println(mc);
        Cover cover = new Cover();
        if (mc == null || mc.isEmpty()) {
            String imageSrc = message.getImgSrc();
            cover = new Cover("" + UUID.randomUUID(), imageSrc, "image/jpeg", message.getId(), "" + UUID.randomUUID());
            cover.setMid(message.getId());
            cover.setDeleted(1);
            coverService.save(cover);
        } else {
            cover = new Cover((String) mc.get("name"), (String) mc.get("url"), (String) mc.get("type"), message.getId(), (String) mc.get("uid"));
            cover.setMid(message.getId());
            cover.setDeleted(1);
            coverService.save(cover);
        }
        //附件保存
        List<Map> list = (List<Map>) map.get("list");
        System.out.println(list);
        if (list != null) {
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    String type = (String) list.get(i).get("type");
                    String uid = (String) list.get(i).get("uid");
                    String name = (String) list.get(i).get("name");
                    String url = (String) list.get(i).get("src");
                    Files files = new Files();
                    files.setFileName(name);
                    files.setFileUrl(url);
                    files.setFileType(type);
                    files.setFileUid(uid);
                    files.setDeleted(1);
                    files.setMid(message.getId());
                    files.setFileTime(DateUtil.formatMinute(new Date()));
                    filesService.save(files);
                }
            }
        }
        return new Result<>().success();
    }

    @ApiOperation(value = "删除新闻")
    @PostMapping("/delete")
    @RequiresAuthentication
    @RequiresPermissions("message")
    @ResponseBody
    @CrossOrigin
    public Result<?> messageDelete(@RequestBody Map map) {
        Object res = map.get("message");
        Message message = JSON.parseObject(JSON.toJSONString(res), Message.class);
        message.setDeleted(0);
        messageService.updateById(message);
        QueryWrapper<Cover> coverQueryWrapper = new QueryWrapper<>();
        coverQueryWrapper.eq("mid", message.getId());
        coverService.remove(coverQueryWrapper);
        QueryWrapper<Files> filesQueryWrapper = new QueryWrapper<>();
        filesQueryWrapper.eq("mid", message.getId());
        filesService.remove(filesQueryWrapper);
        return new Result<>().success();
    }

    @ApiOperation(value = "更新新闻")
    @PostMapping("/update")
    @RequiresAuthentication
    @RequiresPermissions("message:edit")
    @ResponseBody
    @CrossOrigin
    public Result<?> messageUpdate(@CurrentUser User user, @RequestBody Map map0) {
        Map map = (Map) map0.get("map");
        Object message1 = map.get("message");
        Message message = JSON.parseObject(JSON.toJSONString(message1), Message.class);
        List<Role> roles = userRoleService.queryRolesByUserId(user.getUserId());
        Role role = roles.get(0);
        messageService.updateById(message);
        //封面保存,如果封面为null,则从imgSrc拿封面
        Cover cover = new Cover();
        Map mc = (Map) map.get("cover");
        System.out.println("**************");
        System.out.println(mc);
        if (mc == null || mc.isEmpty()) {
            String imageSrc = message.getImgSrc();
            cover = new Cover("" + UUID.randomUUID(), imageSrc, "image/jpeg", message.getId(), "" + UUID.randomUUID());
            cover.setMid(message.getId());
            cover.setDeleted(1);
            coverService.updateByMid(cover);
        } else {
            cover = new Cover((String) mc.get("name"), (String) mc.get("url"), (String) mc.get("type"), message.getId(), (String) mc.get("uid"));
            cover.setMid(message.getId());
            cover.setDeleted(1);
            coverService.updateByMid(cover);
        }
        //附件保存
        List<Map> list = (List<Map>) map.get("list");
        System.out.println("**************");
        System.out.println(list);
        QueryWrapper<Files> filesQueryWrapper = new QueryWrapper<>();
        filesQueryWrapper.eq("mid", message.getId());
        filesService.remove(filesQueryWrapper);
        if (list != null) {
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    String type = (String) list.get(i).get("type");
                    String uid = (String) list.get(i).get("uid");
                    String name = (String) list.get(i).get("name");
                    String url = (String) list.get(i).get("src");
                    Files files = new Files();
                    files.setFileName(name);
                    files.setFileUrl(url);
                    files.setFileType(type);
                    files.setFileUid(uid);
                    files.setDeleted(1);
                    files.setMid(message.getId());
                    files.setFileTime(DateUtil.formatMinute(new Date()));
                    filesService.save(files);
                }
            }
        }
        return new Result<>().success();
    }


    @ApiOperation(value = "新闻审核通过")
    @PostMapping("/update/success")
    @RequiresAuthentication
    @RequiresPermissions("message:edit")
    @ResponseBody
    @CrossOrigin
    public Result<?> messageAuditingSuccess(@RequestBody Map map) {
        int id = (int) map.get("id");
        Message message = messageService.getById(id);
        message.setState("1");
        messageService.updateById(message);
        return new Result<>().success();
    }

    @ApiOperation(value = "新闻审核不通过")
    @PostMapping("/update/fail")
    @RequiresAuthentication
    @RequiresPermissions("message:edit")
    @ResponseBody
    @CrossOrigin
    public Result<?> messageAuditingFail(@RequestBody Map map) {
        int id = (int) map.get("id");
        Message message = messageService.getById(id);
        message.setState("3");
        messageService.updateById(message);
        return new Result<>().success();
    }

    @ApiOperation(value = "根据级别获取新闻")
    @GetMapping("/getMessageList")
    @RequiresAuthentication
    @RequiresPermissions("message")
    @ResponseBody
    @CrossOrigin
    public Result<?> getMessageListByRole(@CurrentUser User user) {

        List<Role> roles = userRoleService.queryRolesByUserId(user.getUserId());
        Role role = roles.get(0);

        //获取新闻,要么匹配角色,要么角色等级高于发布人角色等级,如校级是1,那么等级比他低的,如2,3,4,5都是能够被查看的
        QueryWrapper<Message> messageQueryWrapper = new QueryWrapper<>();
        messageQueryWrapper.and(qq -> qq.eq("publisher_rank", role.getRoleName()).eq("deleted", 1))
                .or(pp -> pp.gt("publisher_level", role.getRoleLevel()).eq("deleted", 1));
        List<Message> list = messageService.list(messageQueryWrapper);
        List<Message> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Message message = list.get(i);
            String str = message.getTypePath();
            String[] res = str.split("/");
            ArrayList<String> list2 = new ArrayList<String>();
            int sum = res.length;
            String p = null;
            if (sum == 0) {
                list2.add("/");
            } else {
                for (int j = 1; j < sum; j++) {
                    for (int k = 1; k <= j; k++) {
                        if (k == 1) {
                            p = "/" + res[k];
                        } else
                            p += "/" + res[k];
                    }
                    list2.add(p);
                }
            }
            message.setPathList(list2);
            String userImg = userService.getUserImg(message.getUserName());
            message.setUserImg(userImg);
            QueryWrapper<MessageType> messageTypeQueryWrapper = new QueryWrapper<>();
            messageTypeQueryWrapper.eq("type_path", message.getTypePath());
            MessageType messageType = messageTypeService.getOne(messageTypeQueryWrapper);
            message.setTypeName(messageType.getTypeName());
            list1.add(message);
        }
        return new Result<>().success().put(list1);
    }


    @ApiOperation(value = "根据id获取新闻内容")
    @GetMapping("/examine")
    @RequiresAuthentication
    @RequiresPermissions("message")
    @ResponseBody
    @CrossOrigin
    public Result<?> getMessageById(Integer id) {
        Message message = messageService.getById(id);
        String str = message.getTypePath();
        String[] res = str.split("/");
        ArrayList<String> list2 = new ArrayList<String>();
        int sum = res.length;
        String p = null;
        if (sum == 0) {
            list2.add("/");
        } else {
            for (int j = 1; j < sum; j++) {
                for (int k = 1; k <= j; k++) {
                    if (k == 1) {
                        p = "/" + res[k];
                    } else
                        p += "/" + res[k];
                }
                list2.add(p);
            }
        }
        message.setPathList(list2);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("message", message);
        //封面文件读取
        QueryWrapper<Cover> coverQueryWrapper = new QueryWrapper<Cover>();
        coverQueryWrapper.eq("mid", id);
        coverQueryWrapper.eq("deleted", 1);
        Cover cover = coverService.getOne(coverQueryWrapper);
        hashMap.put("cover", cover);
        //附件读取
        QueryWrapper<Files> filesQueryWrapper = new QueryWrapper<>();
        filesQueryWrapper.eq("mid", id);
        filesQueryWrapper.eq("deleted", 1);
        List<Files> filesList = filesService.list(filesQueryWrapper);
        hashMap.put("fileList", filesList);
        return new Result<>().success().put(hashMap);
    }

    @ApiOperation(value = "根据级别获取未审核的新闻")
    @GetMapping("/getMessageListNotAudit")
    @RequiresAuthentication
    @RequiresPermissions("message")
    @ResponseBody
    @CrossOrigin
    public Result<?> getMessageListNotAuditByRole(@CurrentUser User user) {
        List<Role> roles = userRoleService.queryRolesByUserId(user.getUserId());
        Role role = roles.get(0);
        QueryWrapper<Message> messageQueryWrapper = new QueryWrapper<>();
        messageQueryWrapper.and(qq -> qq.eq("publisher_rank", role.getRoleName()).eq("deleted", 1).eq("state", "2"))
                .or(pp -> pp.gt("publisher_level", role.getRoleLevel()).eq("deleted", 1).eq("state", "2"));
        List<Message> list = messageService.list(messageQueryWrapper);
        List<Message> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Message message = list.get(i);
            String str = message.getTypePath();
            String[] res = str.split("/");
            ArrayList<String> list2 = new ArrayList<String>();
            int sum = res.length;
            String p = null;
            if (sum == 0) {
                list2.add("/");
            } else {
                for (int j = 1; j < sum; j++) {
                    for (int k = 1; k <= j; k++) {
                        if (k == 1) {
                            p = "/" + res[k];
                        } else
                            p += "/" + res[k];
                    }
                    list2.add(p);
                }
            }
            message.setPathList(list2);
            String userImg = userService.getUserImg(message.getUserName());
            message.setUserImg(userImg);
            System.out.println(message);
            list1.add(message);
        }
        return new Result<>().success().put(list1);
    }
}
